package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.CategoryService;
import lombok.RequiredArgsConstructor;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Delete;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 分类管理
 */
@RestController
@RequestMapping("/category")
@RequiredArgsConstructor
@Slf4j
public class CategoryController {
    private final CategoryService categoryService;

    @PostMapping
    public R<String> save(@RequestBody Category category) {
        log.info("category = {}", category);
        //1：这里我认为先判断一下类别名是否重复然后进行新增  前面已经有一个重复的异常的处理类了
//        Category judge = categoryService.judge(category);
//    if (judge!=null){
//        return R.error("分类名称重复");
//    }
        categoryService.save(category);
        return R.success("新增分类成功");
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize) {
        log.info("page={},pageSize={}", page, pageSize);
        //1：构建分页构造器
        Page<Category> pageinfo = new Page<>(page, pageSize);
        //2:构造条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //3：添加排序条件
        queryWrapper.orderByAsc(Category::getSort);
        //4:执行分页查询
        categoryService.page(pageinfo, queryWrapper);
        return R.success(pageinfo);
    }

    /**
     * 删除分类
     */
    @DeleteMapping
    public R<String> delete(Long ids) {
        log.info("删除分类id={}", ids);
        categoryService.move(ids);
        return R.success("分类信息删除成功");
    }

    /**
     * 根据id修改分类信息
     */
    @PutMapping
    public R<String> update(@RequestBody Category category) {
        log.info("修改分类信息{}",category );
        //调用service方法
        categoryService.updateById(category);
        return R.success("修改分类信息成功");
    }
    /**
     * 新增菜品时发送的请求  根据条件查找一个分类数据
     */
    @GetMapping("/list")
    public R<List<Category>> select(Category category){

        //1:构造一个条件构造器
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(category.getType()!=null,Category::getType,category.getType());
        //1.2:添加排序字段
        lambdaQueryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        //2:根据前端传来的id，；来判断是返回的是所有的菜品的分类，还是套餐的分类
        List<Category> list = categoryService.list(lambdaQueryWrapper);
        return R.success(list);
    }

}
